package com.itheima.controller;

import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

@RestController
@RequestMapping(path = "/sms")
public class SmsController {

    @Autowired
    private JedisPool jedisPool;

    /**
     * 发送短信验证码
     *
     * @param phone
     * @return
     */
    @PostMapping(path = "/sendCode")
    public Result sendCode(String phone) {
        try {
            //生成6位随机数字验证码
            String numeric = RandomStringUtils.randomNumeric(6);
            //调用工具类发送验证码
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, phone, numeric);
            //将发送的验证码保存在redis, 方便后期校验
            jedisPool.getResource().set(phone + RedisConstant.SENDTYPE_ORDER, numeric);
            //验证码有效时间5分钟 , 5分钟后自动过期
            jedisPool.getResource().expire(phone + RedisConstant.SENDTYPE_ORDER, 60 * 5);

            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception exception) {
            exception.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }

    /**
     * 发送短信验证码
     *
     * @param phone
     * @return
     */
    @PostMapping(path = "/sendLoginCode")
    public Result sendLoginCode(String phone) {
        try {
            //生成6位随机数字验证码
            String numeric = RandomStringUtils.randomNumeric(6);
            //调用工具类发送验证码
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, phone, numeric);
            //将发送的验证码保存在session, 方便后期校验
            jedisPool.getResource().set(phone + RedisConstant.SENDTYPE_LOGIN, numeric);
            //验证码有效时间5分钟 , 5分钟后自动过期
            jedisPool.getResource().expire(phone + RedisConstant.SENDTYPE_LOGIN, 60 * 5);

            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception exception) {
            exception.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }
}
